<template>
  <Drawer v-model="Dmodal"
    title="选择奖品"
    :mask-closable="false"
    class="shopDrawer"
    @on-close="close"
    width="1034">
    <div class="search-box">
      <Row type="flex">
        <Row type="flex"
          justify="start"
          class="search-item-left">
          <Col class="search-item">
            <span class="search-label">商品名称:</span>
            <Input placeholder="请输入"
              v-model="keywords"></Input>
          </Col>
          <Col class="search-item" style="display: flex; align-items: center">
            <span class="search-label">商品分类:</span>
            <vueTreeselectChoice
              v-model="classify"
              :disable-branch-nodes="true"
              @input="seleted"
              :options="classifyList"
              permissionCode='1'></vueTreeselectChoice>
          </Col>
          <Col class="search-item">
            <Button class="search-btn"
              type="primary"
              @click="drawSearch">查询</Button>
          </Col>
          <Col class="search-item">
            <Button class="search-btn"
              @click="drawReset">重置</Button>
          </Col>
        </Row>
      </Row>
    </div>
    <Table stripe
      class="table-list drawTable"
      :max-height="drawTableHeight"
      :loading="loading"
      :columns="columns"
      :data="drawData">
      <template slot-scope="{ row }" slot="productImg">
        <img :src="row.productImgs[0]" alt="" height="60">
      </template>
      <template slot-scope="{ row, index }" slot="radio">
        <Radio v-model="row.$checked" @on-change="radioChange(...arguments, index)"></Radio>
      </template>
    </Table>
    <Row type="flex">
      <Col span="24">
        <div class="page-box">
          <Page :total="drawTotal"
            :page-size="drawPageSize"
            :current="drawPageIndex"
            show-total
            show-sizer
            @on-change="changeDrawPageIndex"
            @on-page-size-change="changeDrawPageSize"/>
        </div>
      </Col>
    </Row>
    <Row type="flex"
      justify="end"
      class="bottom-form-item"
      style="width: 100%; padding: 20px 30px; border-top: 1px solid #e8eaec; position: absolute; right: 0; bottom: 0;">
      <Col>
        <Button style="width: 80px"
          @click="close">取消</Button>
        <Button type='primary'
          style="margin-left: 20px; width: 80px"
          @click="ensure">确定</Button>
      </Col>
    </Row>
  </Drawer>
</template>

<script>
import { mapState } from 'vuex'
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
import { cardGoods, cardGoodsType } from '@/api/market/cardactivity/card.js'
export default {
  name: 'selectAward',
  components: { vueTreeselectChoice },
  data () {
    return {
      Dmodal: false,
      keywords: '',
      loading: false,
      classify: null,
      classifyList: [],
      columns: [
        {
          title: ' 单选',
          slot: 'radio',
          width: 60
        },
        {
          title: '商品编码',
          key: 'productSku',
          width: 200
        },
        {
          title: '商品主图',
          slot: 'productImg',
          width: 200
        },
        {
          title: '商品名称',
          key: 'productName',
          minWidth: 300
        },
        {
          title: '商品分类',
          key: 'categoryName',
          width: 120
        },
        {
          title: '原价(元)',
          key: 'price',
          width: 120
        }
      ],
      drawData: [],
      drawTableHeight: 200,
      drawTotal: 0,
      drawPageSize: 10,
      drawPageIndex: 1,
      drawChecked: {}
    }
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    selectIndex: {
      type: Number,
      default: 0
    },
    allForm: {
      type: Array
    },
    shopId: {
      type: String
    }
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId
    })
  },
  watch: {
    show (val) {
      this.Dmodal = val
    },
    shopId (val) {
      if (val) {
        this.getEnums()
        this.drawReset()
      }
    },
    selectIndex (val) {
      const item = this.allForm[val]
      if (item) {
        this.drawChecked = {
          productName: item.awardName,
          productImgs: [item.awardPic],
          productSku: item.skuId,
          categoryCode: item.categoryId,
          price: item.awardPrice
        }
        this.drawReset()
      }
    }
  },
  mounted () {
    this.calcDrawTableHeight()
    window.addEventListener('resize', this.calcDrawTableHeight)
  },
  methods: {
    getEnums () {
      function fliterItem (item) {
        if (!item) return null
        item.id = item.categoryCode
        item.orgName = item.categoryName
        if (item.children && item.children.length) {
          item.childList = item.children.map(ele => {
            let newImte = fliterItem(ele)
            return newImte
          })
        }
        return item
      }
      cardGoodsType({
        merchantId: this.merchantId,
        shopId: this.shopId
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.classifyList = (result.data || []).map(item => {
            let newImte = fliterItem(item)
            return newImte
          })
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    seleted () {
      this.drawSearch()
    },
    radioChange (val, index) {
      if (val) {
        this.drawData = this.drawData.map(item => {
          item.$checked = false
          return item
        })
        this.drawData[index].$checked = val
        this.drawChecked = this.drawData[index]
      }
    },
    ensure () {
      if (this.drawChecked.productSku) {
        let flag = true
        this.allForm.forEach((item, index) => {
          if (item.skuId === this.drawChecked.productSku && index !== this.selectIndex) {
            flag = false
          }
        })
        if (flag) {
          this.$emit('ensure', this.drawChecked)
        } else {
          this.$Message.error('选择奖品重复')
        }
      } else {
        this.$Message.error('请选择奖品')
      }
    },
    close () {
      this.$emit('close')
    },
    drawSearch () {
      this.drawPageIndex = 1
      this.drawGetData()
    },
    drawReset () {
      this.keywords = ''
      this.classify = null
      this.drawSearch()
    },
    changeDrawPageIndex (page) {
      this.drawPageIndex = page
      this.drawGetData()
    },
    changeDrawPageSize (size) {
      this.drawPageSize = size
      this.drawSearch()
    },
    drawGetData () {
      this.loading = true
      this.drawData = []
      cardGoods({
        offset: (this.drawPageIndex - 1) * this.drawPageSize,
        limit: this.drawPageSize,
        productName: this.keywords,
        categoryCode: this.classify,
        merchantId: this.merchantId,
        shopId: this.shopId
      }).then(res => {
        this.loading = false
        const result = res.data || {}
        if (result.status === 200) {
          this.drawData = result.data || []
          this.drawData = this.drawData.map(item => {
            return {
              ...item,
              $checked: item.productSku === this.drawChecked.productSku
            }
          })
          this.drawTotal = result.totalCount || 0
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.loading = false
        this.$Message.error(`${err}`)
      })
    },
    calcDrawTableHeight () {
      const clientHeight = document.documentElement.clientHeight || document.body.clientHeight
      this.drawTableHeight = clientHeight - 300
    }
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.calcDrawTableHeight)
  }
}
</script>

<style lang="less">
  .drawTable.ivu-table-wrapper {
    overflow: hidden !important;
  }
</style>
